package com.aiYouPms.admin.controller;

import com.aiYouPms.admin.dto.RoleCreateParams;
import com.aiYouPms.admin.dto.RoleSearchParams;
import com.aiYouPms.admin.dto.RoleUpdateParams;
import com.aiYouPms.common.api.HttpResult;
import com.aiYouPms.common.api.PageResult;
import com.aiYouPms.common.model.AdminUser;
import com.aiYouPms.common.model.Role;
import com.aiYouPms.common.service.RoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.relational.core.sql.In;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@Controller
@ResponseBody
@RequestMapping("/role")
public class RoleController {

    private final RoleService roleService;

    @Autowired
    public RoleController(RoleService roleService) {
        this.roleService = roleService;
    }

    /**
     * 条件查询角色
     *
     * @param roleName 角色名称（可选）
     * @param roleCode 角色编码（可选）
     * @param status   状态（可选）
     * @return 角色列表
     */
    @GetMapping("/search")
    public HttpResult<PageResult<Role>> search(
            @RequestParam(value = "roleName",defaultValue ="", required = false) String roleName,
            @RequestParam(value = "roleCode", defaultValue ="",required = false) String roleCode,
            @RequestParam(value = "status",defaultValue ="", required = false) Integer status,
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize
    ) {

        Role role = new Role();
        role.setRoleName(roleName);
        role.setRoleCode(roleCode);
        role.setStatus(status);

        PageHelper.startPage(pageNum, pageSize);
        List<Role> roles = roleService.search(role);
        PageInfo<Role> pageInfo = new PageInfo<>(roles);
        PageResult<Role> pageResult = PageResult.of(
                pageInfo.getList(),
                pageInfo.getTotal(),
                pageNum,
                pageSize);

        return HttpResult.success(pageResult);
    }


    /**
     * 根据ID获取角色详情
     *
     * @param id 角色ID
     * @return 角色详情
     */
    @GetMapping("/info/{id}")
    public HttpResult<Role> getRoleById(@PathVariable Integer id) {
        Role role = roleService.findById(id);
        if (role == null) {
            return HttpResult.error("角色不存在");
        }
        return HttpResult.success(role);
    }

    /**
     * 根据角色编码获取角色详情
     *
     * @param roleCode 角色编码
     * @return 角色详情
     */
    @GetMapping("/code/{roleCode}")
    public HttpResult<Role> getRoleByCode(@PathVariable String roleCode) {
        Role role = roleService.findByRoleCode(roleCode);
        if (role == null) {
            return HttpResult.error("角色不存在");
        }
        return HttpResult.success(role);
    }

    /**
     * 创建角色
     *
     * @param roleCreateParams 角色创建参数
     * @return 创建结果
     */
    @PostMapping("/create")
    public HttpResult<Role> createRole(@Validated @RequestBody RoleCreateParams roleCreateParams) {
        Role role = new Role();
        BeanUtils.copyProperties(roleCreateParams, role);
        Role createdRole = roleService.create(role);
        return HttpResult.success("创建成功", createdRole);
    }

    /**
     * 更新角色
     *
     * @param id               角色ID
     * @param roleUpdateParams 角色更新参数
     * @return 更新结果
     */
    @PostMapping("/update/{id}")
    public HttpResult<Role> updateRole(@PathVariable Integer id,
                                       @Validated @RequestBody RoleUpdateParams roleUpdateParams) {
        try {
            Role role = new Role();
            BeanUtils.copyProperties(roleUpdateParams, role);
            Role updatedRole = roleService.update(id, role);
            return HttpResult.success("更新成功", updatedRole);
        } catch (Exception e) {
            log.error("更新角色失败", e);
            return HttpResult.error("更新失败: " + e.getMessage());
        }
    }

    /**
     * 删除角色
     *
     * @param id 角色ID
     * @return 删除结果
     */
    @PostMapping("/delete/{id}")
    public HttpResult<String> deleteRole(@PathVariable Integer id) {
        try {
            roleService.deleteById(id);
            return HttpResult.success("删除成功");
        } catch (Exception e) {
            log.error("删除角色失败", e);
            return HttpResult.error("删除失败: " + e.getMessage());
        }
    }
}